/**
 * 
 */
package com.iwords.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author    	huangbaichuan 
 * @time      	2011-7-23    
 * @description	HTTP-TOOLS  
 */
public class HttpUtils {

    private static final Log log = LogFactory.getLog(HttpUtils.class);

    public static String getResponse(String url) {
        return getResponse(url, "GBK");
    }

    public static String getResponse(String url, String code) {

        try {
            URL getUrl = new URL(url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) getUrl.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("GET");
            httpURLConnection.setRequestProperty("content-type", "text/html");
            httpURLConnection.setConnectTimeout(5000);
            httpURLConnection.setReadTimeout(5000);
            httpURLConnection.connect();

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                InputStream response = httpURLConnection.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(response, code));
                String line = null;
                StringBuilder content = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    content.append(line).append("\n");
                }

                return content.toString();
            }
        } catch (Exception e) {
            log.error("http error!", e);
        }
        return null;
    }
}
